<?php
/**
 * appRain v 0.1.x
 *
 * LICENSE
 *
 * This source file is subject to the MIT license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.opensource.org/licenses/mit-license.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@apprain.com so we can send you a copy immediately.
 *
 * @copyright  Copyright (c) 2010 appRain, Inc. (http://www.apprain.com)
 * @license    http://www.opensource.org/licenses/mit-license.php MIT license
 *
 * HELP
 *
 * Official Website
 * http://www.apprain.com/
 *
 * Download Link
 * http://www.apprain.com/download
 *
 * Documents Link
 * http ://www.apprain.com/documents
 */

class memberController extends appRain_Base_Core
{
    protected $page_title = "Member";
    public $name = "Member";

    /**
     * Example
     * Member Login
     *
     * @return null
     */
    public function loginAction()
    {
        // Set Page meta Information
        $this->page_title           = "Member login";
        $this->page_meta_keyowrds   = "";
        $this->page_meta_desc       = "";

        // Attach some addons
        $this->addons = array('validation.ext','ajaxsubmit');

        // Set variable
        $error = '';

        // Check if any POST data submitted
        if( !empty( $this->data ) )
        {

            // Simple security check
            $username = isset( $this->data['Member']['login_id'] )? $this->data['Member']['login_id'] : '';
            $password = isset( $this->data['Member']['password'] )? $this->data['Member']['password'] : '';

            // Simple validation
            if($username == '' || $password  == '')
            {
                    $error ="Sorry! Invalide Login.";
            }
            else
            {

                // Fetch User data
                $user_arr = $this->Member->find( app::__def()->sysConfig('LOGIN_FIELD') . "='$username'");

                // Check authontication
                if( empty($user_arr))
                {
                    $error ="Sorry! Invalide Login.";
                }
                else if( $user_arr['status'] != "Active")
                {
                    $error ="Sorry! Account not activated.";
                }
                else if(App::Module("Cryptography")->checkEncrypt($password, $user_arr['password']))
                {
                    // Session data set
                    $admin_info_arr = array(
                                    'id' =>  $user_arr['id'],
                                    'f_name' => $user_arr['f_name'],
                                    'l_name' => $user_arr['l_name']
                                );

                    // Register Session data
                    App::Load("Module/Session")->write('AppUser',$admin_info_arr);

                    // redirect to home page
                    $this->redirect('/profile');

                }

            }
        }

        $this->set("selected","login");
        $this->set("section_title","Member Login");
        $this->set('message',$error);

    }

    /**
     * Example
     * Member Logout
     *
     * @return null
     */
   public function logoutAction()
    {
        // Set layout
        $this->layout = "blank";

        App::Load("Module/Session")->delete('AppUser');
        $this->redirect("/");
        exit;
    }

    /**
     * Example
     * Member Forgot Login
     *
     * @return null
     */
       public function forgotloginAction()
		{
			// Set Layout
			$this->layout = "empty";

			if( !empty($this->data))
			{
				try
				{
					if( !App::Load("Helper/Validation")->Email($this->data['Forgotlogin']['login_name']))
					{
						throw new AppException($this->__("Pleaes enter a valid email address."));
					}
					else
					{
						$this->complete_forget_login($this->data['Forgotlogin']['login_name']);
					}

					echo App::Load("Module/Cryptography")->jsonEncode(array("_status" =>"Success","_message"=>$this->__("Password reset instruction sent in your email.")));

				}
				catch (AppException $e)
				{
					echo App::Load("Module/Cryptography")->jsonEncode(array(
																				"_status" => "Error",
																				"_message"=>$e->getMessage()
																			));
				}
			}
		}


		/**
		 * This is an Private function
		 * and it's can't execute by URL because
		 * we did not added the extension "Action" end of
		 * function.
		 * It's a Law of MVC pattern in appRain. This
		 * low save us from unauthorize function
		 * call.
		 */
		private function complete_forget_login($email = "")
		{
			// Fetch data by Email Address
			$member_info = App::Load("Model/Member")->findByEmail($email);

			if(empty($member_info))
			{
				// Throw exception to return in Catch block
				throw new AppException($this->__("No member found with this email address."));
			}
			else
			{
				// Set new Reset for the user to be
				// used in Varification
				$resetid = App::Helper('Date')->getTime();
				App::Load("Model/Member")->setId($member_info['id'])
										 ->setResetid($resetid)
										 ->Save();
				// Set email notificatin
				App::Helper('EmailTemplate')->setParameters(Array(
																	'FirstName'=>$member_info['f_name'],
																	'LastName'=>$member_info['l_name'],
																	'Email'=>$member_info['email'],
																	'PasswordResetLink'=> App::Helper("Html")->linkTag($this->baseurl("/member/passwordreset/" . base64_encode($resetid)),$this->__("Reset Password"))
															))
											->setTo(array($member_info['email'],"{$member_info['f_name']} {$member_info['l_name']}"))
											->prepare(
													  $tempalteName = 'ForgotPassword',
													  $isNotified = true);
			}
		}

		/**
		 * Password Reset Action
		 */
		public function passwordresetAction($restKey = NULL)
		{
			$this->addons = array('validation.ext','ajaxsubmit');
			// Fetch Member by reset Id
			$memberData = App::Model('Member')->findByResetid(base64_decode($restKey));

			if(!empty($memberData))
			{
				if(!empty($this->data))
				{
					$this->layout = 'empty';
					try
					{
						if($this->data['Forgotlogin']['new_password'] != $this->data['Forgotlogin']['re_new_password'])
						{
							throw new AppException($this->__('Password did not match'));
						}
						else
						{
							App::Model('Member')->setId($memberData['id'])
												->setPassword(App::Module("Cryptography")->encrypt($this->data['Forgotlogin']['new_password']))
												->setResetid('')
												->Save();

							echo App::Load("Module/Cryptography")->jsonEncode(Array("_status"=>"Redirect","_location"=>$this->baseurl("/member/login")));
						}

					}
					catch (AppException $e)
					{
						echo App::Load("Module/Cryptography")->jsonEncode(Array("_status"=>"Error","_message"=>$e->getMessage()));
					}

				}
			}
			else App::Helper('Config')->transfer($this->baseurl('/'),"Link expired!"); // Fancy redirection

			$this->set('restKey',$restKey);
		}

      /**
     * Member Registration Action
	 *
     */
    public function signupAction()
    {
		$this->page_title = $this->__("Member Registration");
        $this->addons = array('defaultvalues','validation.ext','ajaxsubmit');
        $this->set("selected","signup");

        if( !empty( $this->data ) )
        {
            $this->layout = 'empty';
            try
            {
                // Execute Signup Process
				$this->completeAjaxSignup();

                echo App::Load("Module/Cryptography")->jsonEncode(Array("_status"=>"Success","_message"=>$this->__("Registration done successfully. Please check your mail.")));
            }
            catch (AppException $e)
            {
                echo App::Load("Module/Cryptography")->jsonEncode(Array("_status"=>"Error","_message"=>$e->getMessage()));
            }
        }
    }

	/**
     * This is a private function and
     * it can not be execute from Url
     */
    private function completeAjaxSignup()
    {
		$capacha = App::Module('Session')->read('capacha');
        if($capacha['memberregi']  != $this->data['Member']['capacha']) throw new AppException($this->__('Please fillup the capacha text correctly'));
		
        // Set Signupdate and standard password
		$this->data['Member']['signup_date'] = App::Load("Helper/Date")->getDate('Y-m-d');
        $this->data['Member']['password'] = App::Module("Cryptography")->encrypt($this->data['Member']['password']);
		// Set resetid
		$resetid = App::Helper('Date')->getTime();
		$this->data['Member']['resetid'] = $resetid;
		// Save Member Data
        $errors = $this->Member
                       ->Save($this->data)
                       ->getErrorInfo();

		if(empty($errors))
        {
			// Send Email
			App::Helper('EmailTemplate')->setParameters(Array(
																'FirstName'=>$this->data['Member']['f_name'],
																'LastName'=>$this->data['Member']['l_name'],
																'Email'=>$this->data['Member']['email'],
																'VerificationLink'=> App::Helper("Html")->linkTag($this->baseurl("/member/verifybyemail/" . base64_encode($resetid)),$this->__("Complete your registration"))
														))
										->setTo(array($this->data['Member']['email'],"{$this->data['Member']['f_name']} {$this->data['Member']['l_name']}"))
										->prepare('MemberRegistration',
												  $isNotified = true);

        }
        else
        {
			// Throw Exception imploding all Model Errors
            throw new AppException(implode("<br>",$errors));
        }
    }

	/**
	 * Verify Registration
	 */
	public function verifybyemailAction($resetkey=null)
	{
		$this->layout = 'empty';
		App::MemberManager()->verifyRegistrationByResetkey($resetkey);
	}
	/**
	 * Profile
	 */
	public function profileAction($id = "")
	{
		if($id == "")
		{
			$id = App::MemberManager()->AppUserloggedInId();
		}

		$memberData = $this->Member->findById($id);
		$this->set('memberData',$memberData);

		$this->set("section_title","Profile");
        $this->set("selected","download");
		$this->set("id","$id");
	}


    /**
     * Manage user infornmation by user panel
     *
     * @parameter action string
     * @return null
     */
    public function accountAction($action = 'view')
    {
        $this->layout = 'admin';
        $this->admin_tab = 'usersetting';

        if( $action =='edit')
        {
            $this->addons = array('validation.ext');
        }

        $message = '';
        if(!empty($this->data))
        {
            $this->Member->save($this->data);
            $message = "Account information saved successfullly";
        }

        $member_info = $this->memberManager()
                            ->thisMember();

        $this->set('member_info',$member_info);
        $this->set('action',$action);
        $this->set('message',$message);
    }

    /**
     * Chagne password
     *
     * @return null
     */
   public function change_passwordAction()
    {
        $this->layout = 'admin';
        $this->admin_tab = 'usersetting';
       $this->addons = array('validation.ext');
        $member_info = $this->memberManager()
                            ->thisMember();
        $message = Array();
        if( !empty($this->data))
        {
            if( $this->data['Member']['old_password']  == '' ||  $this->data['Member']['new_password']  == '' ||  $this->data['Member']['re_new_password'] == '')
            {
                $message  = Array("type"=>"error","msg" => "Field can not be empty.");
            }
            else if(!App::Module("Cryptography")->checkEncrypt($this->data['Member']['old_password'],$member_info['password']))
            {
                $message  = Array("type"=>"error","msg" => "The old password did not matched.");
            }
            else if ($this->data['Member']['new_password'] != $this->data['Member']['re_new_password'])
            {
                $message  = Array("type"=>"error","msg" => "New password did not match.");
            }
            else
            {
                $this->Member
                     ->setId($member_info['id'])
                     ->setPassword(App::Module("Cryptography")->encrypt($this->data['Member']['new_password']))
                     ->Save();

                $message  = Array("type"=>"success","msg" => "Password changed successfully");
            }
        }

        $this->set('message',$message);
    }

    /**
     * Example
     * Manage Member
     *
     * @parameter action string
     * @parameter id integer
     * @return null
     */
    public function manageAction( $action = NULL, $id = NULL)
    {
        /*
         * Set Layout admin admin tab
         */
        $this->setAdminTab('usermanagement');
        $error = "";

        /*
         * Attached Plugins during Add or Update data
         * For View addmin common admin functions
         */
        if($action == 'update')
        {
            $this->addons = array('validation.ext');
        }
        else
        {
            $this->addons = array('row_manager');
        }

        /*
         * Saving data if any POST request appear
         */
        if( !empty($this->data))
        {
            $error = $this->Member->save($this->data)
                           ->getErrorInfo();
            if(empty($error))
            {
                $this->redirect("/member/manage");
                exit;
            }
        }

        /*
         * Feach Data for view
         */
        if( $action == 'view' || $action == 'update' )
        {
            /*
             * Data for singal Entry
             */
            $data = $this->memberManager()
            			 ->Members($id);
        }
        else
        {
            /*
             * List user data
             */
            $data = $this->Member->paging("1",$this->get_config('default_pagination'));
        }

        $this->set('error', $error);
        $this->set('data_list', $data);
        $this->set( 'action', $action );
    }
}
